<template>
  <div class="login">
    <el-form :label-position="labelPosition" label-width="auto" :model="loginFormInfo" style="max-width: 300px">
      <div class="title">高级系统</div>
      <el-form-item label="账号" :label-position="itemLabelPosition">
        <el-input v-model="loginFormInfo.username" />
      </el-form-item>
      <el-form-item label="密码" :label-position="itemLabelPosition">
        <el-input v-model="loginFormInfo.password" />
      </el-form-item>
      <el-form-item>
        <el-space :size="30">
          <el-input v-model="loginFormInfo.captcha" />
          <el-image :src="loginFormInfo.authCodeImg" @click="getAuthCode" />
        </el-space>
      </el-form-item>
      <el-button type="primary" @click="login" style="width: 300px">登录</el-button>
    </el-form>
  </div>
</template>

<style>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20%;
}
.title {
  text-align: center;
  margin-bottom: 5%;
  font-size: 20px;
  color: rgb(0, 0, 0);
  font-family: '华文行楷';
}
</style>

<script lang="ts" setup>
  import { onMounted, reactive, ref } from 'vue'
  import type { FormItemProps, FormProps } from 'element-plus'
  import { ElMessage } from 'element-plus'
  import { getAuthCodeQuest, loginApi } from '@/api/login';

  const labelPosition = ref<FormProps['labelPosition']>('right')
  const itemLabelPosition = ref<FormItemProps['labelPosition']>('')
  const loginFormInfo = reactive({
    username: '',
    password: '',
    captcha: '',
    authCodeImg: '',
  })

  /**
   * 使用onMounted作为Composition API的钩子来执行挂载后的代码
   */
  onMounted(() => {
    getAuthCode();
  })

  /**
   * 登录
   */
  const login = () => {
    loginApi({
      username: loginFormInfo.username,
      password: loginFormInfo.password,
      captcha: loginFormInfo.captcha,
      checkKey:1
    })
    .then((res) => {
      if (res.code == 200) {
        console.log("TOKEN:"+res.result.token);
        ElMessage({
          message: res.message,
          type: 'success',
        })
        return;
      }
      ElMessage.error(res.message)
      getAuthCode();
    })
  }

  /**
   * 获取验证码
   */
  const getAuthCode = () => {
    getAuthCodeQuest().then((res) => {
      loginFormInfo.authCodeImg = res.result;
    })
  }
</script>

